package web.weibo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
import web.weibo.mapper.MapperUser;
import web.weibo.model.User;
import web.weibo.model.UserRole;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import static web.weibo.service.ServiceWeibo.formattedTime;

@Controller
public class ControllerPublic {

    private MapperUser mapperUser;

    public ControllerPublic(MapperUser mapperUser) {
        this.mapperUser = mapperUser;
    }

    @GetMapping("/")
    public ModelAndView index() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String createdTime = sdf.format(date);
        ModelAndView modelAndView = new ModelAndView("index");
        modelAndView.addObject("message", "欢迎来到微博!");
        modelAndView.addObject("createdTime", createdTime);
        return modelAndView;
    }

    /**
     * 管理员权限功能
     * @param request
     * @return
     */
    @GetMapping("/admin")
    public ModelAndView routeAdmin(HttpServletRequest request) {
        User currentUser = ControllerHelper.currentUser(this.mapperUser, request);
        if (currentUser.role == UserRole.admin) {
            // 获取当前登录用户
            ArrayList<User> users = this.mapperUser.users();
            ModelAndView modelAndView = new ModelAndView("admin");
            modelAndView.addObject("currentUser", currentUser);
            modelAndView.addObject("users", users);
            return modelAndView;
        } else {
            String message = "您没有管理员权限!";
            String createdTime = formattedTime();
            ModelAndView modelAndView = new ModelAndView("index");
            modelAndView.addObject("message", message);
            modelAndView.addObject("createdTime", createdTime);
            return modelAndView;
        }
    }
}
